package org.funtester.performance.books.chapter01.section4;

import java.util.concurrent.PriorityBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

/**
 * 多优先级线程池使用示例
 */
public class PriorityTaskDemo {

    public static void main(String[] args) {
        ThreadPoolExecutor executor = new ThreadPoolExecutor(0, 2, 60L, TimeUnit.SECONDS, new PriorityBlockingQueue<Runnable>());// 创建线程池,核心线程数0,最大线程数2,线程空闲时间60秒,任务队列为优先级阻塞队列
        for (int i = 0; i < 5; i++) {// 提交5个任务
            int priorityLevel = 5 - i;// 优先级递增
            executor.execute(new PriorityRunnable(priorityLevel) {// 提交任务,优先级递增
                @Override
                public void run() {
                    try {
                        Thread.sleep(1000);// 休眠1秒,模拟任务执行时间
                    } catch (InterruptedException e) {
                        throw new RuntimeException(e);
                    }
                    System.out.println(Thread.currentThread().getName() + "  " + System.currentTimeMillis() + "  " + priorityLevel + "  执行任务");// 打印任务执行信息
                }
            });
            System.out.println(Thread.currentThread().getName() + "  " + System.currentTimeMillis() + "  " + priorityLevel + "  提交任务");// 打印任务提交信息
        }
        executor.shutdown();// 关闭线程池
    }

}
